package com.xinxin.o2o.service.impl;

import com.xinxin.o2o.dto.ProductExecution;
import com.xinxin.o2o.enums.ProductStateEnum;
import com.xinxin.o2o.enums.ProductStatusEnum;
import com.xinxin.o2o.mapper.ProductImgMapper;
import com.xinxin.o2o.mapper.ProductMapper;
import com.xinxin.o2o.model.Product;
import com.xinxin.o2o.model.ProductImg;
import com.xinxin.o2o.service.ProductService;
import com.xinxin.o2o.util.FileUtil;
import com.xinxin.o2o.util.ImageUtil;
import com.xinxin.o2o.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 史鑫鑫
 * @date 2019-08-20 22:55
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    ProductImgMapper productImgMapper;

    @Override
    public ProductExecution getProductList(Product productCondition, int pageIndex, int pageSize) {
        int rowIndex = PageUtil.calculateRowIndex(pageIndex, pageSize);
        List<Product> productList = productMapper.queryProductList(productCondition, rowIndex, pageSize);
        int count = productMapper.queryProductCount(productCondition);
        ProductExecution productExecution = new ProductExecution();
        productExecution.setProductList(productList);
        productExecution.setCount(count);
        return productExecution;
    }

    @Override
    public Product getProductById(long productId) {
        return productMapper.queryProductByProductId(productId);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ProductExecution addProduct(Product product, MultipartFile thumbnail,
                                       List<MultipartFile> productImgs) throws RuntimeException {
        if (product != null && product.getShop() != null && product.getShop().getShopId() != null) {
            product.setCreateTime(new Date());
            product.setUpdateTime(new Date());
            product.setEnableStatus(ProductStatusEnum.OFF_SALE.getState());
            if (thumbnail != null) {
                try {
                    addThumbnail(product, thumbnail);
                } catch (IOException e) {
                    throw new RuntimeException("添加图片失败");
                }
            }
            try {
                int effectedNum = productMapper.insertProduct(product);
                if (effectedNum <= 0) {
                    throw new RuntimeException("创建商品失败");
                }
            } catch (Exception e) {
                throw new RuntimeException("创建商品失败:" + e.toString());
            }
            if (productImgs != null && productImgs.size() > 0) {
                addProductImgs(product, productImgs);
            }
            return new ProductExecution(ProductStateEnum.SUCCESS, product);
        } else {
            return new ProductExecution(ProductStateEnum.EMPTY);
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ProductExecution modifyProduct(Product product, MultipartFile thumbnail,
                                          List<MultipartFile> productImgs) throws RuntimeException {
        if (product != null && product.getShop() != null && product.getShop().getShopId() != null) {
            product.setUpdateTime(new Date());
            if (thumbnail != null) {
                Product tempProduct = productMapper.queryProductByProductId(product.getProductId());
                if (tempProduct.getImgAddr() != null) {
                    FileUtil.deleteFile(tempProduct.getImgAddr());
                }
                try {
                    addThumbnail(product, thumbnail);
                } catch (IOException e) {
                    throw new RuntimeException("修改图片失败");
                }
            }
            if (productImgs != null && productImgs.size() > 0) {
                deleteProductImgs(product.getProductId());
                addProductImgs(product, productImgs);
            }
            try {
                int effectedNum = productMapper.updateProduct(product);
                if (effectedNum <= 0) {
                    throw new RuntimeException("更新商品信息失败");
                }
                return new ProductExecution(ProductStateEnum.SUCCESS, product);
            } catch (Exception e) {
                throw new RuntimeException("更新商品信息失败:" + e.toString());
            }
        } else {
            return new ProductExecution(ProductStateEnum.EMPTY);
        }
    }

    private void addProductImgs(Product product, List<MultipartFile> productImgs) {
        String dest = FileUtil.getShopImagePath(product.getShop().getShopId());
        List<String> imgAddrList = ImageUtil.generateNormalImgs(productImgs, dest);
        if (imgAddrList.size() > 0) {
            List<ProductImg> productImgList = new ArrayList<ProductImg>();
            for (String imgAddr : imgAddrList) {
                ProductImg productImg = new ProductImg();
                productImg.setImgAddr(imgAddr);
                productImg.setProductId(product.getProductId());
                productImg.setCreateTime(new Date());
                productImgList.add(productImg);
            }
            try {
                int effectedNum = productImgMapper.batchInsertProductImg(productImgList);
                if (effectedNum <= 0) {
                    throw new RuntimeException("创建商品详情图片失败");
                }
            } catch (Exception e) {
                throw new RuntimeException("创建商品详情图片失败:" + e.toString());
            }
        }
    }

    private void deleteProductImgs(long productId) {
        List<ProductImg> productImgList = productImgMapper.queryProductImgList(productId);
        for (ProductImg productImg : productImgList) {
            FileUtil.deleteFile(productImg.getImgAddr());
        }
        productImgMapper.deleteProductImgByProductId(productId);
    }

    private void addThumbnail(Product product, MultipartFile thumbnail) throws IOException {
        String dest = FileUtil.getShopImagePath(product.getShop().getShopId());
        String thumbnailAddr = ImageUtil.generateThumbnail(thumbnail.getInputStream(), dest, thumbnail.getOriginalFilename());
        product.setImgAddr(thumbnailAddr);
    }
}
